package sync;

import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Created by zhj on 15-10-26.
 */
public class MySync extends AbstractQueuedSynchronizer {
    MySync(){
        setState(1);
    }

    @Override
    protected int tryAcquireShared(int arg) {
        return super.tryAcquireShared(arg);
    }

    public static void main(String[] args) {
        MySync mySync=new MySync();
        try {
            //等待3s
            mySync.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(123);
        System.out.println(Integer.toBinaryString(10));
    }




























    private final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -990419035911612884L;

        /** 停止状态 */
        private static final int STOP = 0;

        /** 正在运行中 */
        private static final int RUNNING = 1;

        /**
         * 初始化为未运行状态
         */
        Sync() {
            setState(RUNNING);
        }

        /**
         * AQS的惯用法，此处标识当AQS尝试获取共享锁时，是否获取成功，如果当前不处于运行状态，则可以获取
         */
        @Override
        public int tryAcquireShared(int acquires) {
            return getState() != RUNNING ? 1 : -1;
        }

        /**
         * AQS的惯用法，此处标识为释放
         */
        @Override
        public boolean tryReleaseShared(int releases) {
            for (;;) {
                int c = getState();
                if (c != RUNNING)
                    return false;
                if (compareAndSetState(c, STOP)) {
                    return true;
                }
            }
        }
    }
}
